Popular Searches
Popular Course Categories
Popular Courses

Introduction to Processes and Threads

Introduction to Processes and Threads

Multithreading and Concurrency Fundamentals

Introduction to Processes and Threads in Java

Course: Core Java Training

Topic: Introduction to Processes and Threads

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction to Processes and Threads

Processes and threads are fundamental concepts in operating systems and Java programming. They allow computers to execute programs and perform multiple tasks efficiently. Modern applications often need to perform several activities, such as downloading files, processing data, responding to user input, and communicating with servers.

A process is an instance of a running program with its own execution environment and resources. A thread is an individual path of execution within a process. A process can contain one or more threads, and threads belonging to the same process share many of its resources.

Java supports multithreaded programming through the Thread class, the Runnable interface, and higher-level concurrency utilities such as the Executor framework.

2. Learning Objectives

  • Understand the meaning of a process and a thread.
  • Identify the differences between processes and threads.
  • Learn how Java applications execute through the Java Virtual Machine (JVM).
  • Understand concurrency, parallelism, and multitasking.
  • Explore the main benefits and challenges of multithreading.
  • Learn the basic structure of Java thread creation and execution.
  • Understand common thread-related problems and safe programming practices.

3. What Is a Process?

A process is a running instance of a program. When a user starts an application, the operating system creates or launches a process and provides the resources needed to execute it.

A process typically has its own virtual address space, process-specific resources, and at least one thread of execution. The operating system manages processes and allocates CPU time and other resources to them.

Examples of processes

  • A web browser running on a computer.
  • A Java application launched from the command line.
  • A database server processing requests.
  • A media player playing audio or video.
  • A text editor running independently of other applications.

Important characteristics of a process

  • Independent memory space: A process normally has its own virtual address space.
  • Resource ownership: It can own resources such as open files, sockets, and other operating-system handles.
  • Execution state: The operating system tracks whether the process is running, waiting, or terminated.
  • Resource consumption: Processes require memory and operating-system resources.
  • Inter-process communication: Separate processes can exchange information using mechanisms such as pipes, sockets, and shared memory.

4. What Is a Thread?

A thread is a unit of execution within a process. Threads allow different parts of the same application to make progress independently. In Java, threads are represented by the java.lang.Thread class.

Threads within a process share resources such as the process's heap memory and open resources, while each thread has its own execution state and stack. This sharing can make communication efficient, but it also means that multiple threads may access the same data at the same time.

Examples of threads in an application

  • A thread handling user-interface events.
  • A thread downloading data from a server.
  • A thread performing calculations.
  • A thread writing information to a file.
  • A thread processing background tasks.

Important characteristics of a thread

  • Lightweight execution: Creating a thread generally requires fewer resources than creating a separate process.
  • Shared resources: Threads in the same process can access shared objects and heap memory.
  • Independent execution path: Each thread has its own call stack and execution state.
  • Scheduling: The JVM and operating system cooperate to schedule thread execution, depending on the thread type and runtime implementation.
  • Communication: Threads can communicate through shared objects, but appropriate coordination may be necessary.

5. Difference Between Processes and Threads

Basis Process Thread
Definition An instance of a running program. A unit of execution within a process.
Memory Normally has its own virtual address space. Shares process memory with other threads, while maintaining its own stack.
Resource usage Generally requires more resources to create and manage. Generally requires fewer resources than a separate process.
Communication Often uses inter-process communication mechanisms. Can communicate through shared memory and objects.
Isolation Usually provides stronger memory isolation from other processes. Threads share many resources, so errors can affect the whole process.
Failure impact A process failure is often isolated from unrelated processes. An uncaught failure or serious problem may affect the entire application process.
Examples Browser process, Java application process. Background worker thread, request-processing thread.

6. Understanding the JVM and Threads

When a Java application is launched, the operating system starts a process for the Java runtime. The Java Virtual Machine executes the application's bytecode and manages runtime services such as memory allocation and thread execution.

The thread that begins executing the application's main() method is commonly called the main thread. A Java application can create additional threads to execute tasks concurrently.

A simplified execution flow is:

Java Source Code (.java)
        |
        v
Java Compiler (javac)
        |
        v
Bytecode (.class)
        |
        v
JVM Running in a Process
        |
        v
Main Thread and Additional Threads
        |
        v
Program Tasks Execute

A JVM process can contain multiple application threads and runtime threads. The precise number and implementation details depend on the JVM and operating system.

7. What Is Multitasking?

Multitasking is the ability of a computer system to manage multiple tasks during overlapping periods. The operating system schedules execution so that applications and threads can make progress.

For example, a user may listen to music while browsing the internet and downloading a file. These activities can be managed by different processes and threads.

Types of multitasking

  • Process-based multitasking: Multiple processes execute or make progress during overlapping periods.
  • Thread-based multitasking: Multiple threads within a process execute or make progress during overlapping periods.

On a single CPU core, the operating system may switch between runnable tasks to share processor time. On a multicore system, multiple threads or processes can execute simultaneously on different cores.

8. Understanding Concurrency

Concurrency means that multiple tasks can make progress during overlapping periods. The tasks may take turns using a processor or may execute on different processors or cores.

Concurrency is useful when an application must handle several activities without waiting for each one to finish before beginning another.

Example of concurrency

Consider a Java application that downloads a file while displaying progress information to the user. One thread can perform the download while another thread updates the interface. The application remains responsive while the download is in progress.

Task 1: Download file  ---- work ---- wait ---- work
Task 2: Update display -- work -- work -- work -- work

The tasks make progress during overlapping periods, even if they are not executing at exactly the same instant.

9. Understanding Parallelism

Parallelism means that multiple tasks execute at the same time, typically on different CPU cores or processors.

For example, a data-processing application may divide a large calculation into smaller independent tasks and process several of them simultaneously on different cores.

Concurrency vs. parallelism

Feature Concurrency Parallelism
Meaning Multiple tasks make progress during overlapping periods. Multiple tasks execute simultaneously.
Hardware requirement Can occur on a single-core processor. Requires multiple execution resources for simultaneous execution.
Primary goal Manage multiple tasks effectively. Perform multiple computations at the same time.
Example Switching between tasks while waiting for network data. Processing separate portions of a calculation on different cores.

10. Introduction to Java Multithreading

Multithreading is the ability of a program to use multiple threads. Java provides built-in support for creating and managing threads, enabling applications to perform independent tasks concurrently.

Multithreading is commonly used in:

  • Web servers and request processing.
  • Background file downloads and uploads.
  • Data processing and computation.
  • Games, animations, and interactive applications.
  • Background logging and scheduled tasks.
  • Applications that communicate with external services.

11. Creating a Thread Using the Thread Class

One way to create a thread is to extend the Thread class and override its run() method. The run() method contains the code that the thread will execute.

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Child thread is running.");
    }
}

public class ThreadExample {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();

        System.out.println("Main thread is running.");
    }
}

Possible output:

Main thread is running.
Child thread is running.

The output order is not guaranteed. The child thread may print its message before or after the main thread prints its message.

Explanation

  • MyThread extends the Thread class.
  • The run() method defines the task.
  • The start() method starts a new thread of execution.
  • The main thread can continue while the new thread executes.

12. Creating a Thread Using the Runnable Interface

Another common approach is to implement the Runnable interface. This separates the task from the thread object and allows the task to be used with different execution mechanisms.

class MyTask implements Runnable {
    @Override
    public void run() {
        System.out.println("Runnable task is running.");
    }
}

public class RunnableExample {
    public static void main(String[] args) {
        MyTask task = new MyTask();
        Thread thread = new Thread(task);

        thread.start();

        System.out.println("Main method continues.");
    }
}

Possible output:

Main method continues.
Runnable task is running.

Again, the exact output order may vary because the scheduler determines when each thread runs.

Why use Runnable?

  • The task logic is separated from thread management.
  • The class can still extend another class because Java supports only single class inheritance.
  • The same task can be submitted to an executor instead of being tied to a manually created thread.
  • It encourages reusable task-oriented design.

13. The Difference Between start() and run()

The methods start() and run() serve different purposes.

Method Description
start() Requests that a new thread be started. The JVM then invokes that thread's run() method.
run() Contains the task's execution logic. Calling it directly behaves like an ordinary method call on the current thread.
Thread thread = new Thread(() -> {
    System.out.println(Thread.currentThread().getName());
});

thread.run();   // Executes in the calling thread
thread.start(); // Starts a separate thread

Calling start() more than once on the same thread object causes an IllegalThreadStateException. Create a new thread object when a new thread execution is required.

14. Basic Thread Lifecycle

Java defines thread states through the Thread.State enumeration. A thread can move between states as it is created, scheduled, blocked, waiting, or completed.

State Description
NEW The thread object has been created, but start() has not been called.
RUNNABLE The thread is executing or is eligible to execute, depending on scheduling.
BLOCKED The thread is waiting to acquire a monitor lock.
WAITING The thread is waiting indefinitely for another thread to perform a particular action.
TIMED_WAITING The thread is waiting for a specified period, such as during sleep().
TERMINATED The thread has completed execution.

These are the official Java thread states. A thread does not have a separate Java state named RUNNING; execution is represented within RUNNABLE.

15. Useful Thread Methods

Method Purpose
start() Starts a thread's execution.
run() Defines the task performed by the thread.
sleep(milliseconds) Pauses the current thread for a specified time, subject to scheduling and timing precision.
join() Waits for another thread to terminate.
isAlive() Checks whether a thread has started and has not yet terminated.
currentThread() Returns a reference to the currently executing thread.
getName() Returns the thread's name.
interrupt() Requests interruption of a thread; the task should respond appropriately.
getState() Returns the thread's current Java state.

16. Example: Running Two Threads

class NumberTask extends Thread {
    private final String taskName;

    NumberTask(String taskName) {
        this.taskName = taskName;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 3; i++) {
            System.out.println(taskName + ": " + i);
        }
    }
}

public class MultipleThreadsExample {
    public static void main(String[] args) {
        NumberTask first = new NumberTask("Task A");
        NumberTask second = new NumberTask("Task B");

        first.start();
        second.start();
    }
}

Possible output:

Task A: 1
Task B: 1
Task B: 2
Task A: 2
Task A: 3
Task B: 3

The output shown is only one possible ordering. Thread scheduling can produce different sequences on different runs. Do not depend on a specific interleaving unless synchronization or another coordination mechanism establishes the required order.

17. Advantages of Multithreading

  • Responsiveness: Background tasks can run without blocking the main activity of an application.
  • Resource sharing: Threads can access shared application data without requiring separate process memory spaces.
  • Improved throughput: Independent tasks may make progress concurrently.
  • Parallel execution: CPU-intensive tasks may run simultaneously on multiple cores.
  • Efficient waiting: A thread waiting for input/output may allow other work to progress.
  • Task separation: Different responsibilities can be organized into independent tasks.

18. Challenges of Multithreading

Although multithreading is useful, it introduces complexity when threads interact with shared state.

  • Race conditions: Results depend on the timing or ordering of concurrent operations.
  • Thread interference: Multiple threads modify shared data in ways that cause incorrect results.
  • Memory visibility problems: One thread may not immediately observe another thread's changes without appropriate synchronization.
  • Deadlock: Threads wait indefinitely for locks held by one another.
  • Starvation: A thread repeatedly fails to obtain the resources or execution time it needs.
  • Debugging difficulty: Thread timing can vary across executions, making bugs hard to reproduce.
  • Resource overhead: Creating too many threads can consume memory and reduce performance.

19. Introduction to Shared Data and Synchronization

Threads in the same process can access shared objects. If two threads update the same variable without proper coordination, the result may be incorrect.

class Counter {
    int count = 0;

    void increment() {
        count++;
    }
}

The statement count++ is not an atomic operation. If multiple threads call increment() concurrently, some updates may be lost.

Synchronization mechanisms such as synchronized, locks, and atomic classes help coordinate access to shared data. The correct choice depends on the requirements of the application.

Example using synchronized

class SafeCounter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}

The synchronized methods use the object's monitor lock, preventing multiple threads from executing these methods on the same object simultaneously. This protects the counter from concurrent updates through these methods.

20. Process Management in Java

Java applications can also start external operating-system processes. The ProcessBuilder class is commonly used to configure and launch another program.

import java.io.IOException;

public class ProcessExample {
    public static void main(String[] args) throws IOException {
        ProcessBuilder builder =
                new ProcessBuilder("java", "-version");

        builder.redirectErrorStream(true);
        Process process = builder.start();

        System.out.println(
            "External process started: " + process.isAlive()
        );
    }
}

This example attempts to launch the Java executable with the -version argument. It assumes that the Java executable is available on the system's executable search path. In production code, configure the executable path as needed and handle the process's output, errors, and exit status appropriately.

Processes and threads solve different execution problems. A process can provide stronger isolation, while threads are often useful for coordinating tasks within one application.

21. Best Practices for Working with Processes and Threads

  • Use threads when independent tasks need to make progress within the same application.
  • Prefer the Executor framework for managing collections of tasks in many application designs instead of creating unlimited threads manually.
  • Protect mutable shared data using appropriate synchronization or concurrency utilities.
  • Do not assume that threads execute in a predictable order.
  • Use join(), futures, or other coordination mechanisms when one task must wait for another.
  • Handle interruption properly rather than silently ignoring interrupt requests.
  • Avoid holding locks for longer than necessary.
  • Use separate processes when stronger isolation or independent execution environments are required.
  • Measure performance before adding concurrency, since coordination and scheduling introduce overhead.

22. Practice Exercises

  1. Write a Java program that creates one thread by extending the Thread class.
  2. Create a second program that implements Runnable and passes its object to a Thread.
  3. Start two threads that print different messages and observe how their output order changes.
  4. Use Thread.currentThread().getName() to display the name of the executing thread.
  5. Write a program that uses join() to wait for a worker thread to complete.
  6. Create a shared counter and investigate what can happen when multiple threads increment it without synchronization.
  7. Explain the difference between concurrency and parallelism using a real-world example.

23. Mini Project: Background Task Simulator

Objective: Build a simple Java application that simulates two background tasks running concurrently.

Requirements:

  • Create a task that simulates downloading a file.
  • Create another task that simulates processing data.
  • Use Runnable to define both tasks.
  • Start both tasks using separate thread objects.
  • Use Thread.sleep() to simulate work that takes time.
  • Handle InterruptedException by restoring the interrupt status and ending the task.
public class BackgroundTaskSimulator {
    public static void main(String[] args) {
        Runnable downloadTask = () -> {
            try {
                for (int i = 1; i <= 3; i++) {
                    System.out.println("Downloading: " + i);
                    Thread.sleep(500);
                }
                System.out.println("Download completed.");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("Download interrupted.");
            }
        };

        Runnable processingTask = () -> {
            try {
                for (int i = 1; i <= 3; i++) {
                    System.out.println("Processing: " + i);
                    Thread.sleep(700);
                }
                System.out.println("Processing completed.");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("Processing interrupted.");
            }
        };

        Thread downloadThread = new Thread(downloadTask);
        Thread processingThread = new Thread(processingTask);

        downloadThread.start();
        processingThread.start();
    }
}

Expected behavior: Downloading and processing messages appear in an interleaved order. The exact order and timing may vary because the threads execute concurrently.

24. Interview Questions and Answers

Q1. What is a process in Java?

A process is an executing program instance managed by the operating system. A JVM running a Java application generally operates within a process.

Q2. What is a thread?

A thread is a unit of execution within a process. Java uses threads to perform tasks concurrently.

Q3. What is the main difference between a process and a thread?

A process normally has its own virtual address space and resources, while threads within a process share many resources but have separate execution stacks and states.

Q4. What is multithreading?

Multithreading is the execution or overlapping progress of multiple threads within one process.

Q5. What is the difference between concurrency and parallelism?

Concurrency means multiple tasks make progress during overlapping periods. Parallelism means multiple tasks execute simultaneously, usually on separate cores or execution resources.

Q6. Why is start() used instead of calling run() directly?

start() initiates a new thread of execution. Calling run() directly executes its code as an ordinary method call on the current thread.

Q7. What is the purpose of the Runnable interface?

Runnable represents a task that can be executed by a thread or submitted to an executor. It separates task logic from thread management.

Q8. What is a race condition?

A race condition occurs when the correctness of a result depends on the timing or ordering of concurrent operations, often because shared mutable data is accessed without adequate coordination.

Q9. What is synchronization?

Synchronization coordinates access to shared data and establishes visibility guarantees between threads. Java provides mechanisms such as synchronized methods and blocks, locks, and atomic classes.

Q10. What is a deadlock?

A deadlock occurs when two or more threads wait indefinitely for resources or locks held by one another, preventing them from making progress.

25. Quick Revision Checklist

  • A process is an executing program instance.
  • A thread is an execution path within a process.
  • Threads in the same process share many resources and objects.
  • Java supports threads through the Thread class and Runnable interface.
  • start() starts a new thread of execution; direct run() calls do not.
  • Concurrency and parallelism are related but different concepts.
  • Shared mutable data may require synchronization.
  • Race conditions, deadlocks, and starvation are common concurrency challenges.
  • The Executor framework can help manage multiple tasks.
  • ProcessBuilder can launch external operating-system processes.

26. Conclusion

Processes and threads are the foundation of concurrent programming in Java. Processes provide execution environments managed by the operating system, while threads allow a program to perform multiple tasks within the same process. Java's thread support makes it possible to build responsive, efficient applications that handle background work and independent tasks.

Understanding process isolation, thread execution, concurrency, parallelism, and synchronization is essential before moving on to advanced topics such as thread lifecycle management, executors, thread pools, locks, and concurrent collections.

Continue learning Core Java: Explore the Core Java Training course, register for a course demo, or visit the JustAcademy website.

Previous Next
whatsapp